//
//  PYShowMediaCell.m
//  IHome
//
//   Created by zhujizheng on 2020/2/18.
//  Copyright © 2019年 com.zhujizheng. All rights reserved.
//

#import "PYShowMediaCell.h"
#import <AVFoundation/AVFoundation.h>
#import "PYMediaInfo.h"
#import "UIImageView+PYMediaInfo.h"

const CGFloat show_image_margin = 10;
const CGFloat min_zoom_scale = 1.2;

@interface PYShowMediaCell () <UIScrollViewDelegate, UIGestureRecognizerDelegate>
/// 图片控件
@property (nonatomic, strong) UIImageView *imgView;
/// 图片缩放控件
@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) UITapGestureRecognizer *doubleTapGesture;
@property (nonatomic, strong) UITapGestureRecognizer *singleTapGesture;
@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;

@end

@implementation PYShowMediaCell

+ (instancetype)cellWithCollectionView:(UICollectionView *)collectionView indexPath:(NSIndexPath *)indexPath
{
    PYShowMediaCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    [cell initScrollView];
    cell.scrollView.frame = CGRectMake(show_image_margin / 2, 0, collectionView.frame.size.width - show_image_margin, collectionView.frame.size.height);
    [cell.scrollView setZoomScale:1 animated:YES];
    cell.scrollView.contentSize = CGSizeMake(collectionView.frame.size.width - show_image_margin, collectionView.frame.size.height);
    return cell;
}

- (void)setMediaInfo:(PYMediaInfo *)mediaInfo
{
    _mediaInfo = mediaInfo;
    PYWeakSelf;
    self.doubleTapGesture.enabled = YES;
    CGSize imgSize = mediaInfo.imgSize;
    if (!(imgSize.width > 0 && imgSize.height > 0) || CGSizeEqualToSize(imgSize, PHImageManagerMaximumSize)) {
        // 有缩略图时，根据缩略图大小更新控件大小
        if (mediaInfo.placeholderImg) imgSize = mediaInfo.placeholderImg.size;
    }
    // 更新控件大小
    [self refreshUIWithImgSize:imgSize];
    [self.imgView py_setMediaInfo:mediaInfo progress:nil completion:^(UIImage * _Nonnull image) {
        if (!image) {
            return;
        }
        PYStrongSelf;
        CGFloat zoomScale = strongSelf.scrollView.zoomScale;
        [strongSelf.scrollView setZoomScale:1 animated:NO];
        [strongSelf refreshUIWithImgSize:image.size];
        [strongSelf.scrollView setZoomScale:zoomScale animated:NO];
    }];
}

- (void)refreshUIWithImgSize:(CGSize)imgSize
{
    if (imgSize.width > 0 && imgSize.height > 0) {
        CGRect frame = AVMakeRectWithAspectRatioInsideRect(imgSize, self.scrollView.bounds);
        self.imgView.frame = frame;
        if (self.mediaInfo.type == PYFileTypeImage) {
            if (self.scrollView.frame.size.width > 0 && self.scrollView.frame.size.height > 0) {
                CGFloat widthRatio = imgSize.width / self.scrollView.frame.size.width;
                CGFloat heightRatio = imgSize.height / self.scrollView.frame.size.height;
                self.scrollView.maximumZoomScale = MAX(MAX(widthRatio, heightRatio), min_zoom_scale);
            }
        }
    }
}

- (UIImageView *)imgView
{
    if (!_imgView) {
        _imgView = [[UIImageView alloc] initWithFrame:AVMakeRectWithAspectRatioInsideRect(CGSizeMake(MIN(APP_WIDTH, APP_HEIGHT), MIN(APP_WIDTH, APP_HEIGHT)), CGRectMake(0, 0, APP_WIDTH, APP_HEIGHT))];
        _imgView.contentMode = UIViewContentModeScaleAspectFit;
        _imgView.backgroundColor = [UIColor blackColor];
    }
    return _imgView;
}

#pragma mark - 双击手势
- (UITapGestureRecognizer *)doubleTapGesture
{
    if (!_doubleTapGesture) {
        _doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGestureAction)];
        _doubleTapGesture.numberOfTapsRequired = 2;
    }
    return _doubleTapGesture;
}

- (void)doubleTapGestureAction
{
    if (self.scrollView.zoomScale == self.scrollView.minimumZoomScale) {
        [self.scrollView setZoomScale:self.scrollView.maximumZoomScale animated:YES];
    } else {
        [self.scrollView setZoomScale:self.scrollView.minimumZoomScale animated:YES];
    }
}
#pragma mark - 单击手势
- (UITapGestureRecognizer *)singleTapGesture
{
    if (!_singleTapGesture) {
        _singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureAction)];
    }
    return _singleTapGesture;
}

- (void)singleTapGestureAction
{
    if ([self.delegate respondsToSelector:@selector(singleTapGestureDidTap:)]) {
        [self.delegate singleTapGestureDidTap:self];
    }
}

#pragma mark - 拖动手势
- (UIPanGestureRecognizer *)panGesture
{
    if (!_panGesture) {
        _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
        _panGesture.delegate = self;
    }
    return _panGesture;
}

- (void)panGestureAction:(UIPanGestureRecognizer *)panGesture
{
    if ([self.delegate respondsToSelector:@selector(collectionViewCell:panGestureDidPanGesture:)]) {
        [self.delegate collectionViewCell:self panGestureDidPanGesture:panGesture];
    }
}

#pragma mark - 长按手势
- (UILongPressGestureRecognizer *)longPressGesture
{
    if (!_longPressGesture) {
        _longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureAction:)];
        _longPressGesture.delegate = self;
    }
    return _longPressGesture;
}

- (void)longPressGestureAction:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state != UIGestureRecognizerStateBegan) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(longPressGestureDidPress:)]) {
        [self.delegate longPressGestureDidPress:self];
    }
}

#pragma mark - scrollView
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(show_image_margin / 2, 0, APP_WIDTH, APP_HEIGHT)];
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        [_scrollView addSubview:self.imgView];
        [_scrollView addGestureRecognizer:self.doubleTapGesture];
        _scrollView.delegate = self;
        [_scrollView addGestureRecognizer:self.panGesture];
        [_scrollView addGestureRecognizer:self.singleTapGesture];
        [self.singleTapGesture requireGestureRecognizerToFail:self.doubleTapGesture];
        [_scrollView addGestureRecognizer:self.longPressGesture];
        [self.singleTapGesture requireGestureRecognizerToFail:self.longPressGesture];
        [self.singleTapGesture requireGestureRecognizerToFail:self.panGesture];
        [self.panGesture requireGestureRecognizerToFail:self.longPressGesture];
        [_scrollView.pinchGestureRecognizer requireGestureRecognizerToFail:_scrollView.panGestureRecognizer];
    }
    return _scrollView;
}

- (void)initScrollView
{
    if (_scrollView) {
        return;
    }
    [self.contentView addSubview:self.scrollView];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imgView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width) ? (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height) ? (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    self.imgView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

@end
